// Time:  O(n)
// Space: O(n)

#include <numeric>
#include <vector>
#include <iostream>
#include <cassert>
using namespace std;

class Solution {
public:
    int candy(vector<int>& ratings) {
        vector<int> candies(ratings.size(), 1);
        for (int i = 1; i < ratings.size(); ++i) {
            if (ratings[i] > ratings[i - 1]) {
                candies[i] = candies[i - 1] + 1;
            }
        }
        for (int i = ratings.size() - 2; i >= 0; --i) {
            if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
                candies[i] = candies[i + 1] + 1;
            }
        }
        return accumulate(candies.cbegin(), candies.cend(), 0);
    }
};


int main() {
    Solution sol;

    // Test case 1
    vector<int> ratings1 = {1, 0, 2};
    int expected1 = 5; // 2 + 1 + 2
    int result1 = sol.candy(ratings1);
    assert(result1 == expected1);
    cout << "Test case 1 passed!" << endl;

    // Test case 2
    vector<int> ratings2 = {1, 2, 2};
    int expected2 = 4; // 1 + 2 + 1
    int result2 = sol.candy(ratings2);
    assert(result2 == expected2);
    cout << "Test case 2 passed!" << endl;

    // Test case 3
    vector<int> ratings3 = {1, 3, 4, 5, 2};
    int expected3 = 11; // 1 + 2 + 3 + 4 + 1
    int result3 = sol.candy(ratings3);
    assert(result3 == expected3);
    cout << "Test case 3 passed!" << endl;

    // Test case 4
    vector<int> ratings4 = {1, 2, 87, 87, 87, 2, 1};
    int expected4 = 13; // 1 + 2 + 3 + 1 + 2 + 3 + 1
    int result4 = sol.candy(ratings4);
    assert(result4 == expected4);
    cout << "Test case 4 passed!" << endl;

    return 0;    
}
